<?php
//SANITIZE ALL ESCAPES
$sanitize_all_escapes = true;
//
//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;
//
// kick out if patient not authenticated
if (isset($_SESSION['pid']) && isset($_SESSION['patient_portal_onsite'])) {
    $pid = $_SESSION['pid'];
}else{
    $pid = $_GET['pid'];
}

$ignoreAuth = true;

//echo $_SESSION['pid'];die;
require_once("../../globals.php");
require_once("$srcdir/forms.inc");
require_once("$srcdir/billing.inc");
require_once("$srcdir/pnotes.inc");
require_once("$srcdir/patient.inc");
require_once("$srcdir/lists.inc");
require_once("$srcdir/acl.inc");
require_once("$srcdir/sql-ledger.inc");
require_once("$srcdir/invoice_summary.inc.php");
require_once("$srcdir/formatting.inc.php");
//require_once("../custom/code_types.inc.php");
require_once("$srcdir/formdata.inc.php");

// "issue" parameter exists if we are being invoked by clicking an issue title
// in the left_nav menu.  Currently that is just for athletic teams.  In this
// case we only display encounters that are linked to the specified issue.
$issue = empty($_GET['issue']) ? 0 : 0 + $_GET['issue'];

//echo $issue;die;

if (isset($_GET['pagesize'])) {
    $pagesize = $_GET['pagesize'];
} else {
    $pagesize = 5;
}

if (isset($_GET['pagestart'])) {
    $pagestart = $_GET['pagestart'];
} else {
    $pagestart = 0;
}

if (isset($_GET['start'])) {
    $start = $_GET['start'] . "-01-01";
    $ano_inicio = $_GET['start'];
} else {
    $start = '2010-01-01';
    $ano_inicio = '2010';
}

if (isset($_GET['end'])) {
    $end = $_GET['end'] . "-12-31";
    $ano_final = $_GET['end'];
} else {
    $end = '2015-12-31';
    $ano_final = '2015';
}

/* echo $_GET['start']." ==> start <br/>";
  echo $_GET['end']." ==> end"; */

$accounting_enabled = $GLOBALS['oer_config']['ws_accounting']['enabled'];
$INTEGRATED_AR = $accounting_enabled === 2;

//maximum number of encounter entries to display on this page:
// $N = 12;
// Get relevant ACL info.
$auth_notes_a = 1;
$auth_notes = 1;
$auth_coding_a = 1;
$auth_coding = 1;
$auth_relaxed = 1;
$auth_med = 1;
$auth_demo = 1;

$tmp = getPatientData($pid, "squad");
/*
  echo "<pre>";
  print_r($tmp);
  echo "</pre>";
  die;
 */
if ($tmp['squad'] && !acl_check('squads', $tmp['squad']))
    $auth_notes_a = $auth_notes = $auth_coding_a = $auth_coding = $auth_med = $auth_demo = $auth_relaxed = 0;

if (!($auth_notes_a || $auth_notes || $auth_coding_a || $auth_coding || $auth_med || $auth_relaxed)) {
    echo "<body>\n<html>\n";
    echo "<p>(" . htmlspecialchars(xl('Encounters not authorized'), ENT_NOQUOTES) . ")</p>\n";
    echo "</body>\n</html>\n";
    exit();
}

// Perhaps the view choice should be saved as a session variable.
//
/* $tmp = sqlQuery("select authorized from users " .
  "where id = ?", array($_SESSION['authUserID']) ); */

/* $billing_view = ($tmp['authorized'] || $GLOBALS['athletic_team']) ? 0 : 1;
  if (isset($_GET['billing']))
  $billing_view = empty($_GET['billing']) ? 0 : 1;
 */
$billing_view = 0;

$drow = false;
if (!$billing_view) {
    // Query the documents for this patient.  If this list is issue-specific
    // then also limit the query to documents that are linked to the issue.
    //echo "PID===> ".$pid;
    $queryarr = array($pid);
    $query = "SELECT d.id, d.type, d.url, d.docdate, d.list_id, c.name " .
            "FROM documents AS d, categories_to_documents AS cd, categories AS c WHERE " .
            "d.foreign_id = ? AND cd.document_id = d.id AND c.id = cd.category_id AND c.id!=10 ";
    if ($issue) {
        $query .= "AND d.list_id = ? ";
        $queryarr[] = $issue;
    }
    $query .= "ORDER BY d.docdate DESC, d.id DESC";
    //echo $query;
    $dres = sqlStatement($query, $queryarr);
    $drow = sqlFetchArray($dres);
}

// $count = 0;

$sqlBindArray = array();

$from = "FROM form_encounter AS fe " .
        "JOIN forms AS f ON f.pid = fe.pid AND f.encounter = fe.encounter AND " .
        "f.formdir = 'newpatient' AND f.deleted = 0 ";
if ($issue) {
    $from .= "JOIN issue_encounter AS ie ON ie.pid = ? AND " .
            "ie.list_id = ? AND ie.encounter = fe.encounter ";
    array_push($sqlBindArray, $pid, $issue);
}
$from .= "LEFT JOIN users AS u ON u.id = fe.provider_id WHERE fe.pid = ? AND fe.date between '" . $start . "' AND '" . $end . "' ";
$sqlBindArray[] = $pid;

$query = "SELECT fe.*, f.user, u.fname, u.mname, u.lname " . $from .
        "ORDER BY fe.date DESC, fe.id DESC";

$countQuery = "SELECT COUNT(*) as c " . $from;


$countRes = sqlStatement($countQuery, $sqlBindArray);
$count = sqlFetchArray($countRes);
$numRes = $count['c'];

if ($pagesize > 0) {
    $query .= " LIMIT " . add_escape_custom($pagestart) . "," . add_escape_custom($pagesize);
}
$upper = $pagestart + $pagesize;
if (($upper > $numRes) || ($pagesize == 0)) {
    $upper = $numRes;
}

//echo $query;
//print_r($sqlBindArray);
$res4 = sqlStatement($query, $sqlBindArray);

$resultados = 0;

// This is called to generate a line of output for a patient document.
//
function showDocument(&$drow) {
    global $ISSUE_TYPES, $auth_med;

    $docdate = $drow['docdate'];
//    echo "docdate: ".$docdate."<br/>";
    $docid = $drow['id'];
    $docdate = substr($docdate, 8, 2) . '/' . substr($docdate, 5, 2) . '/' . substr($docdate, 0, 4);
    $source_entry = $drow['source_entry'];
    /* echo "<pre>";
      print_r($drow);
      echo "</pre>"; */

    echo "<div class='text docrow event' id='" . $drow['id'] . "'>
            <div class='logoDoc'></div>";
    echo "<div><span class='h1 paciente_documento'>Documento - [" . xl_document_category($drow['name']) . "] </span>";
    
        echo "</div>";
    echo "<div class='info' title='Descargar documento'>";

    echo "<a href='../download.php?filename=" . $drow['url'] . "'  rel='" . htmlspecialchars($rawdata, ENT_QUOTES) . "' style='text-decoration: none ! important;'>";
    echo "<div style='padding-left:10px;' class='info_details'>";
    echo "<div  style='cursor: pointer; color: rgb(102, 102, 102);'>";
    echo "- Nombre: " . htmlspecialchars(basename($drow['url']), ENT_NOQUOTES);
    echo "</div>";
    // show associated issue, if any
    if ($auth_med) {
        $irow = sqlQuery("SELECT type, title, begdate " .
                "FROM lists WHERE " .
                "id = ? " .
                "LIMIT 1", array($drow['list_id']));
        if ($irow) {
            $tcode = $irow['type'];
            if ($ISSUE_TYPES[$tcode])
                $tcode = $ISSUE_TYPES[$tcode][2];
            echo htmlspecialchars("$tcode: " . $irow['title'], ENT_NOQUOTES);
        }
    }
    echo "</div>";
    echo "<h2><span style='border-bottom: 1px dashed;cursor:pointer;'>Clic aqu&iacute; para descargar el archivo</span></h2>
								 <p>" . htmlspecialchars($docdate, ENT_NOQUOTES) . "</p>
						</a>
						</div>
					</div>";
    echo '<script type="text/javascript" language="JavaScript">';
    echo "$('#borrar" . $docid . "').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        autoSize: true,
                        type: 'iframe',
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        } // helpers
                    }); // fancybox
                }); // click";
    echo '</script>';
}

function generatePageElement($ano_inicio, $ano_final, $start, $pagesize, $text) {
    if ($start < 0) {
        $start = 0;
    }
    $url = "../patient_file/summary/get_encounters.php?start=" . $_GET['start'] . "&end=" . $_GET['end'] . "&pagestart=" . $start . "&" . "pagesize=" . $pagesize;


    echo "<a href='#' onclick='changePageSizeBtn(" . $ano_inicio . "," . $ano_final . "," . $start . "," . $pagesize . ")' style='display: inline-block; padding: 6px 10px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(49, 182, 172); margin-left: 5px;margin-right: 5px;'>" . $text . "</a>";
}
?>

<link rel="stylesheet" href="<?php echo $GLOBALS['webroot'] ?>/patients/css/encounters.css" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/nightingale.css" >
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jslider.css" >
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jslider.blue.css" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jslider.plastic.css" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jslider.round.css" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jslider.round.plastic.css" type="text/css">

<!--<script type="text/javascript" src="../../library/js/jquery-1.10.1.min.js"></script>-->
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jshashtable-2.1_src.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.numberformatter-1.2.3.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/tmpl.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.dependClass-0.1.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/draggable-0.1.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.slider.js"></script>	

<body class="body_bottom">
    <div id="eventos" class="wrapper_clinico_meds">
        <div id="encounters">
            <div style="width: 100%; margin-bottom: 10px; padding-bottom: 33px; border-bottom: 1px groove;">
                <h1 style="float: left;">
                    <?php
                    echo htmlspecialchars(xl('Past Encounters and Documents'), ENT_NOQUOTES);
                    ?>
                </h1>
                <span style="float:right" class="order">
                    Vista: 
					<a href="#" id="by_date" class="active">Consultas M&eacute;dicas</a>
                    <a href="#" id="by_doc">Documentos</a>
                    <!--<a href="#" id="by_type">Por tipo</a>-->
                </span>
            </div>
            <div id="barra" style="width: 100%; margin-bottom: 10px; padding-bottom: 45px; border-bottom: 1px groove;">
                <div class="layout-slider" style="width: 50%; float: right; margin-bottom: 30px; margin-right: 12px;">
                    <input id="Slider" type="slider" name="area" value="<?php echo $ano_inicio ?>;<?php echo $ano_final ?>" />
                </div>		
                <span style="float: left; font-size: 14px; margin-top: 8px;">
                    Resultados por p&aacute;gina:
                    <select id="selPagesize" pagestart="<?php echo htmlspecialchars($pagestart, ENT_QUOTES); ?>" style="font-size: 10px;" >
                        <?php
                        $pagesizes = array(5, 10, 15, 0);
                        for ($idx = 0; $idx < count($pagesizes); $idx++) {
                            echo "<OPTION value='" . $pagesizes[$idx] . "'";
                            if ($pagesize == $pagesizes[$idx]) {
                                echo " SELECTED='true'>";
                            } else {
                                echo ">";
                            }
                            if ($pagesizes[$idx] == 0) {
                                echo htmlspecialchars(xl('ALL'), ENT_NOQUOTES);
                            } else {
                                echo $pagesizes[$idx];
                            }
                            echo "</OPTION>";
                        }
                        ?>
                    </select>
                </span>
            </div>

            <div id='timeline'>

                <?php
                  
				echo "<div id='docTimeline' style='display:none;'>";
                // This generates document lines as appropriate for the date order.
                while ($drow /* && $raw_encounter_date && $drow['docdate'] > $raw_encounter_date */) {
                    showDocument($drow);
                    $drow = sqlFetchArray($dres);
                    $resultados++;
                }
				echo "</div>";
				
				echo "<div id='dateTimeline'>";
                $i = 0;
                while ($result4 = sqlFetchArray($res4)) {
                    $i++;
                    $resultados++;
                    /* if($i==1){
                      echo "<pre>";
                      print_r($result4);
                      echo "</pre>";
                      } */

                    $reason_string = "";
                    $auth_sensitivity = true;
                    $raw_encounter_date = '';

                    $raw_encounter_date = date("d-m-Y", strtotime($result4["date"]));
                    //echo $raw_encounter_date."<br/>";
                    //$encounter_date = date("D F jS", strtotime($result4["date"]));
                    $reason_string .= htmlspecialchars($result4{"reason"}, ENT_NOQUOTES) . "<br>\n";

                    if ($result4['sensitivity']) {
                        $auth_sensitivity = 1;
                        if (!$auth_sensitivity) {
                            $reason_string = "(" . htmlspecialchars(xl("No access"), ENT_NOQUOTES) . ")";
                        }
                    }


                    /* echo "<pre>";
                      print_r($result4);
                      echo "</pre>"; */

                    // Fetch all forms for this encounter, if the user is authorized to see
                    // this encounter's notes and this is the clinical view.
                    $encarr = array();
                    $encounter_rows = 1;
                    if (!$billing_view && $auth_sensitivity &&
                            ($auth_notes_a || ($auth_notes && $result4['user'] == $_SESSION['authUser']))) {
                        //$encarr = getFormByEncounter($pid, $result4['encounter'], "formdir, user, form_name, form_id, deleted");
                        $encarr = getForm_lists($pid, $result4['encounter'], "formdir, user, form_name, form_id, deleted");
                        $encounter_rows = count($encarr);
                    }

                    $rawdata = $result4['encounter'] . "~" . $raw_encounter_date;
                    //********* MUESTRA LOS DOCS, pero se necesita al menos 1 visita ******/
                    //echo "--".$drow['docdate']."<br/>";
                    //echo "---".$raw_encounter_date."<br/>";
                    $docdate = $drow['docdate'];
                    $docdate = substr($docdate, 8, 2) . '-' . substr($docdate, 5, 2) . '-' . substr($docdate, 0, 4);
                    //echo "-----".$docdate;
                    /* while ($drow && $raw_encounter_date && $docdate > $raw_encounter_date) {
                      showDocument($drow);
                      $drow = sqlFetchArray($dres);
                      $resultados++;
                      } */

                    echo "<div title='Ver detalles' class='encrow text event' id='" . htmlspecialchars($rawdata, ENT_QUOTES) . "'>
						<div class='logo'></div>
						<a class='personPopupTrigger' rel='" . htmlspecialchars($rawdata, ENT_QUOTES) . "' style='text-decoration: none ! important;'>";

                    echo "<div class='info'>
						<span class='h1'>" . $reason_string . "</span>";
                    echo "<div style='padding-left:10px;' class='info_details'>";

                    // Now show a line for each encounter form, if the user is authorized to
                    // see this encounter's notes.
                    $last = "abcdef-123456#$";
                    foreach ($encarr as $enc) {
                        if ($enc['formdir'] == 'newpatient')
                            continue;

                        // skip forms whose 'deleted' flag is set to 1 --JRM--
                        if ($enc['deleted'] == 1)
                            continue;

                        // Skip forms that we are not authorized to see. --JRM--
                        // pardon the wonky logic
                        $formdir = $enc['formdir'];
                        if (($auth_notes_a) ||
                                ($auth_notes && $enc['user'] == $_SESSION['authUser']) ||
                                ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry')))
                            ;
                        else
                            continue;

                        $formdir = $enc['formdir'];
                            //echo "<pre>";print_r($enc);
                            //echo "</pre>";
                        if ($enc['title'] !== $last) {
                           
                            echo "<div>";
                            echo "- " . htmlspecialchars(xl_form_title($enc['title']), ENT_NOQUOTES);
                            echo "</div>";                           
                        }
                        $last = $enc['form_name'];
                    } // end encounter Forms loop
                    echo "</div>";
                    echo "<h2>" . (isset($result4['fname']) ? $result4['fname'] : "") . " " . (isset($result4['lname']) ? $result4['lname'] : "") . ", " . $result4['facility'] . "</h2>
								 <p>" . htmlspecialchars($raw_encounter_date, ENT_NOQUOTES) . "</p>
						
						</div>
						</a>
					</div>";
                } // end while
				echo "</div>";
                if ($resultados == 0) {
                    echo '<div title="Ver detalles" class="event" id="">
					<div class="no-results"></div>
					<div class="info">
						<h2 style="margin-top: 20px; margin-left: 20px;">No se encontraron datos los a&ntilde;os ' . $ano_inicio . ' al ' . $ano_final . '.</h2>
					</div>
				</div>';
                }

                //if ($billing_view && $accounting_enabled && !$INTEGRATED_AR) SLClose();
                ?>

                <?php
                /* PAGINADOR */
                echo "<div id='paginadorDate' style='float:right;margin-top:20px;'>";
                if (($pagesize > 0) && ($pagestart > 0)) {
                    generatePageElement($ano_inicio, $ano_final, $pagestart - $pagesize, $pagesize, " << ");
                }

                echo "<span style='font-size: 14px;'>Mostrando resultados: " . ($pagestart + 1) . " - " . $upper . " de " . $numRes . " consultas m&eacute;dicas</span>";

                if (($pagesize > 0) && ($pagestart + $pagesize <= $numRes)) {
                    generatePageElement($ano_inicio, $ano_final, $pagestart + $pagesize, $pagesize, " &gt;&gt; ");
                }
                echo "</div>";
                /* PAGINADOR */
                ?>
            </div> <!-- end timeline DIV -->

        </div> <!-- end 'encounters' large outer DIV -->
    </div> 
    <div id="examenes" class="wrapper_clinico_meds" class="border title2" style="margin-bottom: 5px;display:none;"></div>
    <div id="problemasClinicos" class="wrapper_clinico_meds" class="border title2" style="margin-bottom: 5px;display:none;"></div>
    <div id="citas" class="wrapper_clinico_meds" class="border title2" style="margin-bottom: 5px;display:none;"></div>
    <div id='tooltipdiv' style='position:absolute;width:400pt;border:1px solid black;padding:2px;background-color:#ffffaa;visibility:hidden;z-index:1000;font-size:9pt;'></div>

</body>

<script language="javascript">
// jQuery stuff to make the page a little easier to use
    $(document).ready(function() {

        jQuery("#Slider").slider({
            from: 1980,
            to: 2015,
            scale: [1980, '|', 1990, '|', 2000, '|', 2010, 2015],
            limits: false,
            step: 5,
            dimension: '',
            skin: "blue",
            callback: function(value) {
                var parts = value.split(";");
                var start = parts[0];
                var end = parts[1];
                pagestart = $("#selPagesize").attr("pagestart");
                pagesize = $("#selPagesize").val();
                var href = "../patient_file/summary/get_encounters.php?start=" + start + "&end=" + end + "&pagestart=" + pagestart + "&pagesize=" + pagesize;
                $("#eventos").load(href);
                //alert(href);
                console.dir(this);
            }
        });

        $("#encounters .event .info").hover(
                function() {
                    $(this).addClass("hover");
                },
                function() {
                    $(this).removeClass("hover");

                }
        );

        $("#selPagesize").change(changePageSize);
       
	   $("#by_date").click(function(e) {
			e.preventDefault();
			$('#docTimeline').hide();
			$('#dateTimeline').show();
			$('#paginadorDate').show();
			$("#by_date").addClass("active");
			$("#by_doc").removeClass("active");
	   });
	   
	   $("#by_doc").click(function(e) {
			e.preventDefault();
			$('#dateTimeline').hide();
			$('#paginadorDate').hide();
			$('#docTimeline').show();
			$("#by_doc").addClass("active");
			$("#by_date").removeClass("active");
			
	   });

        $('.personPopupTrigger').click(function(e) {
            e.preventDefault();
            // format of 'rel' tag: pageid,personguid
            var pageID = $(this).attr('rel');
            var urlID = $(this).attr('id');
            currentID = 1412;
            // If no guid in url rel tag, don't popup blank
            if (currentID == '')
                return;
            var parts = pageID.split("~");
            var enc = parts[0];
            var datestr = parts[1];
            var url = '../patient_file/encounter/forms.php?set_encounter=' + enc;

            //alert(url);
            $("#column_left").load(url);

            /*parent.$.fancybox({
             href: this.href,
             autoSize: true,
             type: 'iframe',
             helpers: {
             overlay: {
             opacity: 0.3,
             css: {
             'background': 'rgba(255, 254, 254,0.85)'
             }
             } // overlay
             } // helpers
             }); // fancybox
             */
        });
       
        refreshSignos();
        refreshMedications();
        refreshAllergies();
        refreshProblemasMedicos();
        refreshPrescriptions();
                
        $("#documentosEncounter").attr("style", "display: none !important");
         $("#documentos").attr("style", "display: block !important");
         
         

    });

    function changePageSize()
    {
        var parts = $("#Slider").val().split(";");
        var start = parts[0];
        var end = parts[1];
        pagestart = $(this).attr("pagestart");
        pagesize = $(this).val();
        var href = "../patient_file/summary/get_encounters.php?start=" + start + "&end=" + end + "&pagestart=" + pagestart + "&pagesize=" + pagesize;
        $("#eventos").load(href);
        //alert(href);
    }

    function changePageSizeBtn(start, end, pagestart, pagesize)
    {
        var parts = $("#Slider").val().split(";");
        var start = parts[0];
        var end = parts[1];
        var href = "../patient_file/summary/get_encounters.php?start=" + start + "&end=" + end + "&pagestart=" + pagestart + "&pagesize=" + pagesize;
        $("#eventos").load(href);
        //alert(href);
    }
</script>

<?php
    if($_REQUEST['reload']==1){
        $_SESSION['encounter'] = 0;
        
    }
?>